package com.pan.exe.driver.impl;

import com.pan.base.RobotUtil;
import com.pan.exe.Executive;
import com.pan.exe.driver.ExecutiveDriver;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class SingleExecutiveDriver implements ExecutiveDriver {

    private final RobotUtil robotUtil = RobotUtil.INSTANCE;

    private ThreadPoolExecutor executor;
    private AtomicInteger flag;

    public SingleExecutiveDriver() {
        flag = new AtomicInteger(1);
        executor = new ThreadPoolExecutor(1,1,120, TimeUnit.SECONDS,new ArrayBlockingQueue<>(1));
    }

    @Override
    public void run(Executive executive) {
        if (flag.compareAndSet(1, 0)) {
            executor.execute(() -> {
                try {
                    executive.run(robotUtil.provideRobot());
                }finally {
                    flag.set(1);
                }
            });
        }
    }

    @Override
    public void close() {
        executor.shutdownNow();
    }
}
